package com.yyx.zookeeperlock.service.Impl;

import com.yyx.zookeeperlock.mapper.ZItemsMapper;
import com.yyx.zookeeperlock.pojo.ZItems;
import com.yyx.zookeeperlock.service.ZookeeperLockService;
import com.yyx.zookeeperlock.utils.DistributedLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ZookeeperLockServiceImpl implements ZookeeperLockService {

    final static Logger log = LoggerFactory.getLogger(DistributedLock.class);

    @Autowired
    private ZItemsMapper zItemsMapper;

    @Autowired
    private DistributedLock distributedLock;

    /**
     * 下订单服务加锁
     * @param itemId
     * @return
     */
    @Override
    public boolean displayBuy(Integer itemId) {
        //获得分布式锁
        distributedLock.getLock();

        int buyCounts = 6;

        //判断库存
        ZItems zItems=zItemsMapper.selectByPrimaryKey(itemId);
        int stockCounts = zItems.getCounts();

        if (stockCounts<buyCounts){
            log.info("库存不足，订单创建失败");
            //释放锁，让下一个请求获得锁
            distributedLock.releaseLock();
            return false;
        }

        //创建订单,伪成功
        boolean isOrderCreated =true;

        //模拟高并发——3s
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
            distributedLock.releaseLock();
        }

        //订单成功，扣除库存
        if (isOrderCreated){
            log.info("订单创建成功");
            zItemsMapper.dispalyReduceCounts(itemId,buyCounts);
        }else {
            log.info("订单创建失败");
            //释放锁，让下一个请求获得锁
            distributedLock.releaseLock();
            return false;
        }


        //释放锁，让下一个请求获得锁
        distributedLock.releaseLock();
        return true;
    }
}
